package 多线程.案例.myThreadPool;
import java.util.concurrent.*;

//模拟实现线程池, 将任务放到线程池中执行任务
public class MyThreadPool {
    //线程安全的队列
    LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

    //分配任务到线程池中运行
    public void submit(Runnable command) throws InterruptedException {
        queue.put(command);
    }

    public MyThreadPool(int n) {
        while (n -- > 0) {
            Thread thread = new Thread(() -> {
                while (! Thread.currentThread().isInterrupted()) {
                    try {
                        Runnable task = queue.take();
                        task.run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
	                    break;
                    }
                }
            });

            thread.start();
        }
    }
}
